<?php

namespace app\api\controller\paotui\poster;

use addons\paotui\library\PosterToken;
use app\admin\model\paotui\PosterExtractType;
use app\admin\model\paotui\PosterLocation;
use app\common\library\Sms;
use think\Validate;
use think\Db;
use fast\Http;
use fast\WXBizDataCrypt;

/**
 * 骑手接口
 */
class Poster extends PosterApi
{
    protected $noNeedLogin = ['mobilelogin','getPhone'];
    protected $noNeedRight = '*';
	
	protected $appid='wxf213ac4571c82d93';
	protected $appsecret='83bb3a3e0acdbecf53efef1ea459e8a6';

    public function _initialize()
    {
        parent::_initialize();
    }

	/**
     * 授权获取手机、openid等
     */
	public function getPhone(){
		$po=request()->post();
		$current=$po['current'];
	
		// $user=Db::name('paotui_poster')->where('mobile','13063501737')->find();
		// $this->auth->direct($user['id']);
		// $userinfo=$this->auth->getUserinfo();
		// $userinfo['nowtype']=$current;
		// $this->success('成功',$userinfo);
		
		if(!$po['iv'] || !$po['encryptedData'] || !$po['code']){
			$this->error('参数错误');
		}else{ 
			$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->appsecret . '&js_code=' . $po['code'] . '&grant_type=authorization_code';
			$res=Http::get($url);
			$rx=json_decode($res,1);
			// p($rx);die;
        
			$pc = new WXBizDataCrypt($this->appid, $rx['session_key']);
			$errCode = $pc->decryptData($po['encryptedData'], $po['iv'], $data );
			if ($errCode == 0) { 
				$rs=json_decode($data,1);
				// p($rs);
				
				$project_id=$po['project_id']?:0;
				$user=Db::name('paotui_poster')->where('mobile',$rs['phoneNumber'])->where("find_in_set($current,type)")->find();
				// p($user);die;
				if(!$user){
					$this->error('您的账号无权登录该系统');
				}
				
				// if(!strstr($user['type'],$current)){
				// 	$this->error('您的账号无该身份权限，请重新选择');
				// }
				Db::name('paotui_poster')->update(['id'=>$user['id'],'openid'=>$rx['openid']]);
				$this->auth->direct($user['id']);
				$userinfo=$this->auth->getUserinfo();
				$userinfo['nowtype']=$current;
				$this->success('成功',$userinfo);
			} else { 
				$this->error('错误：'.$errCode);
			}
		}
	}
    //手机号登录
    public function mobilelogin(){

        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }

        if($captcha != "8888"){
            if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
                $this->error(__('验证码不正确'));
            }
        }

        $posterModel = new \app\admin\model\paotui\Poster();
        $posterInfo = $posterModel->where(['mobile'=>$mobile,'status'=>"1"])->find();
        if (empty($posterInfo)) {
            $this->error(__('当前手机号码还未注册骑手'));
        }
        if(empty($posterInfo['status'])){
            $this->error(__('当前手机号码已被锁定，请联系客服解锁'));
        }

        PosterToken::clear($posterInfo->id);
        $ret = $this->auth->direct($posterInfo->id);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }

    }

    public function logout()
    {
        // p($this->auth->id);die;
        $work = Db::name('paotui_poster')->where(['id'=>$this->auth->id])->update(['is_order'=>0,'updatetime'=>time()]);
         $rx = Db::name('worktime')->where([ 'user_id'=>$this->auth->id])->where('endtime is null')->find();
         if($rx){
              $res = Db::name('worktime')->where(['id'=>$rx['id']])->update(['endtime'=>time()]);
         }
       
        
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 获取快递员信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info(){
        $posterModel = new \app\admin\model\paotui\Poster();
        $posterInfo = $posterModel->where(['id'=>$this->auth->id,'status'=>1])->field("id,poster_name,is_order,mobile")->find();
        if($posterInfo){
            $posterService = new \addons\paotui\service\Poster();
            $posterInfo['todayCompleteNum'] = $posterService->getTodayCompletePostNum($this->auth->id);                  //获取今日完成订单
            $posterInfo['todayMoney'] = $posterService->getTodayMoney($this->auth->id);                                  //今日收益
        }
        //获取所有新订单
        $status = 1;  // 1待抢单 2待揽收 3运输中 4派送中 5已完成 6服务中（2,3,4） -1已取消
        $page = 1;
        $limit = 100;

        $where['poster_id'] = $this->auth->id;

        //获取当前快递员的最近的经纬度
        $posterLocationModel = new PosterLocation();
        $posterLocationInfo = $posterLocationModel->where(['poster_id'=>$this->auth->id])->find();
        $lat = empty($posterLocationInfo['lat'])?0:$posterLocationInfo['lat'];
        $lng = empty($posterLocationInfo['lat'])?0:$posterLocationInfo['lng'];

        $postService = new \addons\paotui\service\Post();
        $datax = $postService->getPosterPostList($status,$where,$page,$limit,"*",$lng,$lat,$this->auth->id);
        
        if($datax['total']>100){
            $posterInfo['total'] = '99+';
        }else{
             $posterInfo['total'] = $datax['total'];
        }
        $posterInfo['all'] = Db::name('paotui_post')->where(['poster_id'=>$this->auth->id])->count();
        // p($posterInfo);die;
        $this->success('请求成功',$posterInfo);
    }


    /**
     * 完善骑手提现类型
     */
    public function extract_type(){
        $bank_name = $this->request->post("bank_name");
        $bank_code = $this->request->post("bank_code");
        $name = $this->request->post("name");
        $wechat = $this->request->post("wechat");
        $alipay = $this->request->post("alipay");
        $alipay_name = $this->request->post("alipay_name");

        $extractTypeModel = new PosterExtractType();
        if($extractTypeInfo = $extractTypeModel->where(['poster_id'=>$this->auth->id])->find()){
            if($extractTypeInfo->save([
                'bank_name'=>$bank_name,
                'bank_code'=>$bank_code,
                'name'=>$name,
                'wechat'=>$wechat,
                'alipay'=>$alipay,
                'alipay_name'=>$alipay_name,
                'updatetime'=>time()
            ])){
                $this->success("操作成功");
            }else{
                $this->error("操作失败");
            }
        }else{
            $extractTypeModel = new PosterExtractType();
            if($extractTypeModel->save([
                'poster_id'=>$this->auth->id,
                'bank_name'=>$bank_name,
                'bank_code'=>$bank_code,
                'name'=>$name,
                'wechat'=>$wechat,
                'alipay'=>$alipay,
                'alipay_name'=>$alipay_name,
                'updatetime'=>time()
            ])){
                $this->success("操作成功");
            }else{
                $this->error("操作失败");
            }
        }

    }

    public function extract_type_info(){
        $extractTypeModel = new PosterExtractType();
        $data = $extractTypeModel->where(['poster_id'=>$this->auth->id])->find();

        $this->success("请求成功",$data);
    }
}
